<?php

class Pixel extends Model_Abstract
{
	public function getPixels($siteid, $pos)
	{
		$sql = "select * from pixels where site_id=? and pos=?";
		try
		{
			return $this->_connection->query($sql,array($siteid, $pos));
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function firePixelOrNot($campaign, $pos)
	{
		
		$cam = empty($campaign['cam']) ?  '' : $campaign['cam'];
		$pub = empty($campaign['pub']) ?  '' : $campaign['pub'];
		$pla = empty($campaign['pla']) ?  '' : $campaign['pla'];
		
		$pixel = $this->getPixelInfo($cam, $pub, $pla);
		// if the current pixel doesn't exist in pixel_managment, always fire it
		if ($pixel === NULL)
		{
			return true;
		}
		if ($pos != $pixel['position'])
		{
			return true;
		}
		$rand = rand(0,99);
		if ($rand < $pixel['peak'])
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	private function getPixelInfo($cam, $pub, $pla)
	{
		$sql = "select * from pixel_managment where campaign=? and pub=? and (pla=? or pla='') order by pla desc";
		try
		{
			$result =  $this->_connection->query($sql,array($cam, $pub, $pla));
			if (count($result) > 0)
				return $result[0];
			return NULL;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
}
?>